﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace SocialKit.LightRest
{
    /// <summary>
    /// Providers extension methods to operate collections.
    /// </summary>
    public static class CollectionExtensions
    {
        /// <summary>
        /// Normalize values collection to a query string format.
        /// </summary>
        /// <param name="values">The values to normalize.</param>
        /// <returns></returns>
        public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> values)
        {
            if (values == null)
                return null;

            if (values.Count() == 0)
                return string.Empty;

            return string.Join("&",
                values.Select(v => string.Format("{0}={1}",
                    RestUtility.UrlEncode(v.Key),
                    RestUtility.UrlEncode(v.Value))).ToArray()
                    );
        }

        /// <summary>
        /// Normalize values collection to a query string format.
        /// </summary>
        /// <param name="values">The values to normalize.</param>
        /// <param name="order">The ascending order function to sort values in the collection.</param>
        /// <returns></returns>
        public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> values, Func<KeyValuePair<string, string>, string> order)
        {
            if (values == null)
                return null;

            if (values.Count() == 0)
                return string.Empty;

            if (order == null)
                throw new ArgumentNullException("order");
                
            return string.Join("&",
                values.OrderBy(order).Select(v => string.Format("{0}={1}",
                    RestUtility.UrlEncode(v.Key),
                    RestUtility.UrlEncode(v.Value))).ToArray()
                    );
        }
    }
}